const fs = require('fs');
const path = require('path');

// See: https://github.com/DeMoorJasper/dart-sass
const sassLocation = path.resolve('input.js'); // require.resolve('sass');
const libLoc = path.join(__dirname, 'lib/index.js');
const prelude = fs.readFileSync(path.join(__dirname, 'prelude.js'), 'utf-8');

try {
  fs.mkdirSync('lib');
} catch (e) {
  /* */
}
fs.copyFileSync(sassLocation, libLoc);

const sassFileContent = fs.readFileSync(libLoc, 'utf-8');

let libraryContent = sassFileContent
  .replace('self.readline = require("readline");', '')
  .replace(`self.chokidar = require("chokidar");`, '')
  .replace(`self.fs = require("fs");`, '')
  .replace(
    'var dartNodePreambleSelf = typeof global !== "undefined" ? global : window;',
    ''
  )
  .replace(
    `var self = Object.create(dartNodePreambleSelf);`,
    `var self = window;`
  );

const nodePolyfillStartIndex = libraryContent.indexOf(
  `// if we're running in a browser, Dart supports most of this out of box`
);
const nodePolyfillEndIndex = libraryContent.indexOf(`// Generated by dart2js`);

libraryContent =
  libraryContent.substr(0, nodePolyfillStartIndex + 1) +
  libraryContent.substr(nodePolyfillEndIndex);

fs.writeFileSync(libLoc, prelude + libraryContent);
